package com.chu.cloud.consumer;

import com.chu.cloud.dto.order.SeckillOrderCreateDto;
import com.chu.cloud.service.OrderService;
import com.chu.cloud.stream.channel.SeckillExecuteProcessor;
import com.chu.cloud.stream.consumer.MessageConsumer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author: Tianshu.CHU
 * @Date: 2018/9/6 16:39
 * @Description:
 */
@Component
@Slf4j
public class SeckillOrderExecuteConsumer implements MessageConsumer<SeckillOrderCreateDto> {

    @Autowired
    private Map<String, OrderService> orderServiceMap;

    private final AtomicInteger num = new AtomicInteger(0);

    @StreamListener(SeckillExecuteProcessor.INPUT)
    @Override
    public void recevieMessage(SeckillOrderCreateDto payLoad) {
        log.info("-----订单微服务收到秒杀订单执行,当前请求数:{}-----", num.incrementAndGet());
        CompletableFuture.runAsync(() -> {
            OrderService orderService = orderServiceMap.get(payLoad.getOrderType().getValue());
            orderService.create(payLoad.getMemberId(), payLoad);
        }).exceptionally(e ->{
            log.error(e.getMessage(),e);
            return null;
        });
    }

}
